#!/usr/bin/env python3
# _*_coding:utf-8_*_

"""
@version: 3.5.2
@author: cockroach 
@contact: donnie.fan@gmail.com
@software: PyCharm
@file: ex_code_xmlmod_5.py
@time: 2017/2/27 15:50
"""

import xml.etree.ElementTree as ET

'''
创建一个xml文件
.SubElement 设置标签关联关系及属性

'''

tree = ET.Element("treelist")
# 设置name标签为 tree 子标签
name = ET.SubElement(tree, "name", attrib={"enrolled": "yes"})

# 设置 age、sex标签为name的子标签
age = ET.SubElement(name,"age", attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")

# 添加标签值
name.text = "hangsan"
sex.text = "F"
age.text = '33'

name2 = ET.SubElement(tree,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
name2.text = "lisi"
age.text = '19'

# 赋值ET.ElementTree(tree) 到et变量
et = ET.ElementTree(tree)
# 写入文件
et.write("test.xml",encoding="utf-8",xml_declaration=True)

# 打印tree内容
ET.dump(tree)